<?php
/**
 * reset_schedule.php
 * 用于每日重置医生排班表 yoshop_goods_weekly_schedule 中昨天对应星期的挂号数。
 * 支持随机/固定配置，无配置默认填 10。
 */
echo 1;die;
// --- 简单认证 ---
$secretKey = 'your_secret_key'; // 修改为你自己的密钥
if (!isset($_GET['key']) || $_GET['key'] !== $secretKey) {
    http_response_code(403);
    die('Unauthorized access');
}

// --- 数据库配置 ---
$db_host = 'localhost';
$db_user = 'yygh_120gcw_com';
$db_pass = 'f52387d4a852aacc';
$db_name = 'yygh_120gcw_com';

$mysqli = new mysqli($db_host, $db_user, $db_pass, $db_name);
if ($mysqli->connect_error) {
    die("数据库连接失败: " . $mysqli->connect_error);
}
$mysqli->set_charset("utf8");

// --- 获取昨天对应的星期几 ---
$yesterday = date('Y-m-d', strtotime('-1 day'));
$week_day = (int) date('N', strtotime($yesterday)); // 1 ~ 7
$update_time = time();

// --- 获取所有医生的排班记录 ---
$sql = "SELECT id, goods_id FROM yoshop_goods_weekly_schedule WHERE week_day = ?";
$stmt = $mysqli->prepare($sql);
$stmt->bind_param("i", $week_day);
$stmt->execute();
$result = $stmt->get_result();

$updated_count = 0;

while ($row = $result->fetch_assoc()) {
    $schedule_id = $row['id'];
    $doctor_id = $row['goods_id'];

    // 默认值
    $new = [
        'morning'   => 10,
        'afternoon' => 10,
        'night'     => 10
    ];

    // 查询号源规则
    $rule_sql = "SELECT section, mode, fixed_num, random_min, random_max 
                 FROM yoshop_doctor_schedule_source_rule 
                 WHERE doctor_id = ? AND week_day = ? AND is_enabled = 1";
    $rule_stmt = $mysqli->prepare($rule_sql);
    $rule_stmt->bind_param("ii", $doctor_id, $week_day);
    $rule_stmt->execute();
    $rules = $rule_stmt->get_result();

    while ($rule = $rules->fetch_assoc()) {
        $section = $rule['section']; // morning/afternoon/night
        if ($rule['mode'] == 'fixed') {
            $new[$section] = (int)$rule['fixed_num'];
        } elseif ($rule['mode'] == 'random') {
            $min = (int)$rule['random_min'];
            $max = (int)$rule['random_max'];
            $new[$section] = rand($min, $max);
        }
    }

    $rule_stmt->close();

    // 更新排班表
    $update_sql = "UPDATE yoshop_goods_weekly_schedule 
                   SET morning_num = ?, afternoon_num = ?, night_num = ?, update_time = ? 
                   WHERE id = ?";
                   var_dump($update_sql);die;
    $update_stmt = $mysqli->prepare($update_sql);
    $update_stmt->bind_param("iiiii", $new['morning'], $new['afternoon'], $new['night'], $update_time, $schedule_id);
    if ($update_stmt->execute()) {
        $updated_count++;
    }
    $update_stmt->close();
}

$stmt->close();
$mysqli->close();

// 输出结果
echo "✅ 排班重置成功！星期 {$week_day}，共更新医生排班记录：{$updated_count} 条。";
?>